package com.zaofan.controller;



import com.zaofan.bean.Account;
import com.zaofan.bean.AccountLog;
import com.zaofan.bean.OrderInfo;
import com.zaofan.bean.OrderPay;
import com.zaofan.dao.AccountDao;
import com.zaofan.dao.AccountLogDao;
import com.zaofan.dao.OrderInfoDao;
import com.zaofan.service.OrderInfoService;
import com.zaofan.service.OrderPayService;
import com.zaofan.utils.JsonUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/** 退款
 * Created by Administrator on 2017/1/18.
 */
@WebServlet("/find_refund")
public class RefundFindController extends BaseServlet{
    static final int LENGTH = 6;   //流水号尾数长度
    static  int nums = 0;          //自动增长值
    private OrderInfoDao orderinfodao= new OrderInfoDao();
    private OrderPayService orderpayserver=new OrderPayService();
    private OrderInfoDao infodao = new OrderInfoDao();
    private AccountDao accountdao =new AccountDao();
    private AccountLogDao logdao =new AccountLogDao();

    private OrderInfoService mOrderInfoService = new OrderInfoService();



    protected void list(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> params = new HashMap<>();
        Enumeration<String> enumeration = request.getParameterNames();
        while (enumeration.hasMoreElements()) {
            String name = enumeration.nextElement();
            Object value = request.getParameter(name);
            params.put(name, value);
        }

        System.out.println("城市id:"+params.get("cityId").toString());
       List<OrderInfo> list =  mOrderInfoService.getCancelOrder(params.get("orderNo").toString(),params.get("mobile").toString()
        ,params.get("cityId").toString(),params.get("payState").toString(),params.get("begin").toString(),params.get("end").toString(),params.get("phone").toString());

        Long count = mOrderInfoService.getCancelOrderCount(params.get("orderNo").toString(),params.get("mobile").toString()
                ,params.get("cityId").toString(),params.get("payState").toString(),params.get("phone").toString());



        JsonUtils.writeSuccessPageJson("查询成功", list, count,Integer.parseInt(params.get("cityId").toString()),response);






    }

 protected void torefund(HttpServletRequest request,HttpServletResponse response){
         Map<String, Object> params = new HashMap<>();
         Enumeration<String> enumeration = request.getParameterNames();
         while (enumeration.hasMoreElements()) {
             String name = enumeration.nextElement();
             Object value = request.getParameter(name);
             params.put(name, value);
         }
          Object str = params.get("datails");




          String[] ss=str.toString().split("#");
          List <OrderPay> aliList =new ArrayList<>();
          List <OrderPay> weiXinList=new ArrayList<>();
          List <OrderPay> AccoundPay=new ArrayList<>();
         for(int i=1;i<ss.length;i++){
                 System.out.println(ss[i]);
             OrderPay op=orderpayserver.findByorderNo(ss[i]);
             System.out.println(op.getPayMethod());
            if((op!=null)&&(!op.equals(""))){


             if(op.getPayMethod().equals("微信支付")){
                  weiXinList.add(op);
             }
             else if(op.getPayMethod().equals("支付宝支付")){
                  aliList.add(op);
             }else if(op.getPayMethod().equals("账户余额支付")){
                  AccoundPay.add(op);
             }
             else{
               System.out.println("未知的付款方式:可能未记录付款方式!");

             }}
             else{System.out.println("查询订单详情失败!:订单详情表单不存在或已经退款!");  }
         }
         if(aliList.size()>0){
               String s  =dataHandleAliPay(aliList);
                   System.out.println(s);

             JsonUtils.writeSuccessJsonActionPage(s,"1",response);
         }
         if(weiXinList.size()>0){
         dataHandleWeiXinPay(weiXinList);
             JsonUtils.writeSuccessJsonActionPage(null,"0",response);
         }
         if(AccoundPay.size()>0){
         dataHandleAccoundPay(AccoundPay);
             JsonUtils.writeSuccessJsonActionPage(null,"0",response);
         }
         JsonUtils.writeSuccessJsonActionPage(null,"0",response);
     }




    //进行支付宝退款请求参数拼接
    private String dataHandleAliPay(List<OrderPay> list){
          System.out.println(list.size()+"-支付宝退款");
          String batch_no=getBatchNo();
          int nums=list.size();

          StringBuffer  url= new StringBuffer();
          StringBuffer  datail=new StringBuffer();
          url.append("/api_test.jsp?");
          url.append("WIDbatch_no=");
          url.append(batch_no);
          url.append("&&WIDbatch_num=");
          url.append(nums);
          url.append("&&WIDdetail_data=");
        for(int i=0;i<nums;i++){
            if(i<nums-1){

                OrderPay op=list.get(i);
                datail.append(op.getTradeNo());
                datail.append("^");
                datail.append(op.getPayPrice());
                datail.append("^");
                datail.append("协商退款");
                datail.append("|");}
            if(i==nums-1){
                OrderPay op=list.get(i);
                datail.append(op.getTradeNo());
                datail.append("^");
                datail.append(op.getPayPrice());
                datail.append("^");
                datail.append("协商退款");


            }
        }
        url.append(datail);

        return url.toString();
    }
    //微信退款操作
    private String dataHandleWeiXinPay(List <OrderPay> list){
          System.out.println(list.size()+"-微信退款操作+1");

        //successChangeState()

        return null;
    }


    //账户余额退款操作
    private String dataHandleAccoundPay(List<OrderPay> lists){
        for (OrderPay op: lists
             ) {
            String orderno = op.getOrderNo();
            orderinfodao.updateRefund(orderno);
            OrderInfo info = infodao.findParentByOrderNo(orderno);
            Account user =accountdao.findAccountById(info.getAccountId());
            AccountLog log = new AccountLog();

            log.setAccountId(user.getId());
            log.setAccountMobile(user.getMobile());
            log.setAddTime(new Date());
            log.setType("订单取消,已经退款至余额");
            log.setMoney(info.getPayPrice());
            log.setBeforeMoney(user.getMoney());
            log.setAfterMoney(user.getMoney().add(info.getPayPrice()));

            logdao.add(log);
            user.setMoney(user.getMoney().add(info.getPayPrice()));
            accountdao.update(user);
            op.setPayState("完成退款");
            successChangeState(op);
            System.out.println(op.getTradeNo()+"-进行余额退款操作+1");

            op.setPayState("已经退款");
            orderpayserver.update(op);
        }


       return null;
    }
    // 更新已经退款的账单
    private void successChangeState(OrderPay orderPay){

        orderpayserver.update(orderPay);

         }
    //按照城市寻找退款的账单
     private List<OrderPay> findRefundByCity (List<OrderPay> list,String cityId){

         List<OrderPay>  arraylist= new ArrayList();
         for (OrderPay op:list) {
             OrderInfo oif =  orderinfodao.findByOrderNo( op.getOrderNo());
             if(Integer.toString(oif.getCityId()).equals(cityId)){
                 arraylist.add(op);
             }
         }

         return arraylist;


     }

    // 生成流水号 格式  yyyyMMdd+6位  用于查询退款进度。
    private String getBatchNo(){
        String  num="";

        SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");
        String temp = sf.format(new Date());
        String str = String.valueOf(++nums);

        int len = str.length();
        if (len >= LENGTH) {// 取决于业务规模
            return str;
        }
        int rest = LENGTH - len;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < rest; i++) {
            sb.append('0');
        }
        sb.append(str);
        sb.toString();
        num=temp+sb;
        return num;
    }
}

